package cn.yuanqiao.cqbc.util;
/**
 * @author 赵常飞
 * @date 2024/6/17 15:58
 */

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;

/**
 *@Author: 赵常飞
 *@Date: 2024/6/17 15:58
 *@Description:
 *@Note:
 */

public class ZipUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ZipUtils.class);
    /*
     * zip 解压缩中文文件名会乱码 需要指定GBK
     * */
    public static void unzip(ZipFile zipFile, File outFile) {
        try {
            String encoding = zipFile.getEncoding();
            LOGGER.info("压缩文件 解压编码 = " + encoding);
            Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
            while (entries.hasMoreElements()) {
                ZipArchiveEntry zipArchiveEntry = entries.nextElement();
                boolean directory = zipArchiveEntry.isDirectory();
                String zipArchiveEntryName = zipArchiveEntry.getName();
                LOGGER.info("文件或目录名称 = " + zipArchiveEntryName);
                Path path = Paths.get(outFile.getPath(), zipArchiveEntryName);
                if (directory) {
                    LOGGER.info("zipArchiveEntry 文件目录 = " + path);
                    if (Files.notExists(path)) {
                        Files.createDirectories(path);
                    }
                } else {
                    LOGGER.info("zipArchiveEntry 文件路径 = " + path);
                    if (Files.notExists(path.getParent())){
                        Files.createDirectories(path.getParent());
                    }
                    if (Files.exists(path)){
                        Files.delete(path);
                    }
                    try (InputStream inputStream = zipFile.getInputStream(zipArchiveEntry)) {
                        FileCopyUtils.copy(inputStream, new FileOutputStream(path.toFile()));
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("解压文件失败：", e);
        }
    }

    public static void unzip(File inFile, File outFile) {
        try {
            unzip(new ZipFile(inFile, "GBK"), outFile);
        } catch (IOException e) {
            throw new RuntimeException("解压文件失败：", e);
        }
    }

    public static void unzip(String zipFilePath, String outFileDir) {
        unzip(new File(zipFilePath), new File(outFileDir));
    }
}
